﻿using System;
using System.Collections.Generic;
using System.Web;
using MuzoBlog.Core.BussinessLogic.Blog;
using System.IO;
using Muzo.Core.Helpers;

namespace MuzoBlog.Core
{
    public class MuzoApp : HttpApplication
    {
        private static string BlogDataXmlPath = HttpContext.Current.Server.MapPath("~/App_Data/BlogData/BlogData.xml");
        private static string BlogDataXmlBackupPath = HttpContext.Current.Server.MapPath("~/App_Data/BlogData/BlogData_backup.xml");

        public static BlogData Db { get; set; }

        static MuzoApp()
        {}

        #region HttpApplication Methods
        
        public void Application_Start(object sender, EventArgs args)
        {
            if (File.Exists(BlogDataXmlPath))
            {
                // TODO: Load current data to memory
                Load();
                // Blog = Load();
            }
        }

        public void Application_BeginRequest(object sender, EventArgs args)
        {
            // Check blog is installed
            if (Db == null && !Request.RawUrl.Contains("/Install/"))
                Response.Redirect("~/Install/Default.aspx", true);

        }

        public void Application_End(object sender, EventArgs args)
        {
            Application.Lock();
            Save();
            Application.UnLock();
        }

        #endregion

        #region SaveLoad

        /// <summary>
        /// Saves blogdata(db) to xml file
        /// </summary>
        public static void Save()
        {
            if (File.Exists(BlogDataXmlPath))
                File.Copy(BlogDataXmlPath, BlogDataXmlBackupPath);

            FileInfo fileInfo = new FileInfo(BlogDataXmlPath);
            if (!Directory.Exists(fileInfo.DirectoryName))
                Directory.CreateDirectory(fileInfo.DirectoryName);

            FileHelper.SetText(BlogDataXmlPath, SerializationHelper.XmlSerialize(Db));
        }

        /// <summary>
        /// Loads blogdata(db) from xml file
        /// </summary>
        private static void Load()
        {
            if (!File.Exists(BlogDataXmlPath) && Db == null)
                throw new Exception("Blog data file not found!");

            Db = SerializationHelper.XmlDeSerialize<BlogData>(FileHelper.GetText(BlogDataXmlPath));
        }

        #endregion
    }
}